package com.stylefeng.guns.common.util;

import java.util.Date;

public class InviteUtil {
    public static void main(String[] args) {
        Date sigmastart = new Date();
        System.out.println("生成邀请码:" + createInviteCode(800000));
        System.out.println("生成邀请码:" + createInviteCode(1500625));
        System.out.println("生成邀请码:" + createInviteCode(15006250));
        System.out.println("生成邀请码:" + createInviteCode(55006250));
        System.out.println("解密邀请码:" + deInviteCode(createInviteCode(1500625)));
        System.out.println("解密邀请码:" + deInviteCode(createInviteCode(52521874)));
        Date sigmaend = new Date();
        System.out.println("耗时:" + (sigmaend.getTime() - sigmastart.getTime()) + "毫秒");
    }

    /**
     * createInviteCode:(根据用户ID生成验证码). <br/>
     * 采用35进制法
     *
     * @param userID 用户ID
     * @return
     * @author zgr
     */
    public static String createInviteCode(Integer userID) {
        String sourceString = "E5FCDG3HQA4B1STUV67MWX89KLYZNOPIJ2R";
        String code = "";
        Integer num = userID;
        while (num > 0) {
            Integer mod = num % 35;
            code = sourceString.substring(mod, mod + 1) + code;
            num = (num - mod) / 35;
        }
        if (code.length() < 5) {
            code = addZeroForNum(code, 5);
        }
        return code;
    }

    /**
     * deCode:(根据验证码返回用户ID). <br/>
     * 35进制转10进制
     *
     * @param code 用户ID
     * @return
     * @author zgr
     */
    public static Integer deInviteCode(String code) {
        String sourceString = "E5FCDG3HQA4B1STUV67MWX89KLYZNOPIJ2R";
        // 把0去掉
        code = code.replaceAll("0", "");
        Integer len = code.length();
        Integer id = 0;
        //从低位向高位计算
        for (int i = 0; i < len; i++) {
            String temp = code.substring(len - i - 1, len - i);
            System.out.println(temp + " " + sourceString.indexOf(temp));
            id += sourceString.indexOf(temp) * (int) (Math.pow(35, i));
        }
        return id;
    }

    public static String addZeroForNum(String str, int strLength) {
        int strLen = str.length();
        if (strLen < strLength) {
            while (strLen < strLength) {
                StringBuffer sb = new StringBuffer();
                sb.append("0").append(str);// 左补0
                // sb.append(str).append("0");//右补0
                str = sb.toString();
                strLen = str.length();
            }
        }
        return str;
    }
}